var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var app = express();
// 引入jwt token工具
const JwtUtil = require('./utils/jwt');
// 返回格式
const BizResult = require("./config/BizResult");

const { onVerifyUrlList } = require('./utils/enumeration');


//导入cors包
const cors = require('cors')
// 使用cors包解决跨域问题
app.use(cors())

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

var accountRouter = require('./routes/account');
var userRouter = require('./routes/user');
var categoryRouter = require('./routes/category');
var systemRouter = require('./routes/system');
var friendRouter = require('./routes/friend');




// 引入定时任务
const cron = require('node-cron');

// 每十分钟执行一次：在每个小时的第0分钟、第10分钟、第20分钟...第50分钟执行
cron.schedule('*/10 * * * *', () => {
  console.log('任务每十分钟执行一次。');
  // 在这里编写你想要定时执行的代码
});



// 验证token
app.use(function (req, res, next) {
  if (onVerifyUrlList.find(e => e == req.url)) {//判断请求地址是否验证token
    next();
  } else {
    let token = req.headers.token;
    let jwt = new JwtUtil(token);
    let result = jwt.verifyToken();
    console.log(result);
    // 如果考验通过就next，否则就返回登陆信息不正确
    if (result == null || !result) {
      res.status(500).send(BizResult.bizFail({
        code: 999,
        msg: '登录已过期，请重新登录'
      }));
    } else {
      console.log('token验证通过')
      next();
    }
  }
});


app.use('/', accountRouter);
app.use('/user', userRouter);
app.use('/category', categoryRouter);
app.use('/system', systemRouter);
app.use('/friend', friendRouter);





// 处理跨域问题
app.all('*', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  res.header('Access-Control-Allow-Headers', ['mytoken', 'Content-Type']);
  next();
});

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
